package day03;

import exception.DataAccessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String path = request.getServletPath();

        System.out.println(path);

        if ("/add.emp".equals(path)) {
            add(request, response);
        }

        if ("/list.emp".equals(path)) {
            list(request, response);
        }

        if ("/remove.emp".equals(path)) {
            remove(request, response);
        }

        if ("/load.emp".equals(path)) {
            load(request, response);
        }

        if ("/modify.emp".equals(path)) {
            modify(request, response);
        }

        if("/showUploadphoto.emp".equals(path)){
            showUploadphoto(request, response);
        }


        if("/uploadphoto.emp".equals(path)){
            uploadphoto(request, response);
        }
    }

    protected void uploadphoto(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("EmpServlet.uploadphoto()");



        DiskFileItemFactory factory = new DiskFileItemFactory();


        //解析工具
        ServletFileUpload fileUpload = new ServletFileUpload(factory);


        String photoName=null;
        Integer id=null;



        try {
            List<FileItem> items = fileUpload.parseRequest(request);

            //因为返回的是List类型
            //跟以前request.getParameter()操作Map结果不一样
            //使用起来不方便
            //自己转换成Map
            Map<String, FileItem> map = new HashMap<String, FileItem>();
            for (FileItem item : items) {
                // System.out.println(item.getFieldName());
                map.put(item.getFieldName(), item);
            }


            id=Integer.parseInt(map.get("id").getString());


            FileItem photo=map.get("photo");


            if(photo.getSize()>(25*1024)){
                request.setAttribute("message","头像图片大小小于25k");
                request.getRequestDispatcher("/emp/uploadphoto.jsp").forward(request,response);
                return;
            }

            String uploadDir=getServletContext().getRealPath("photo");

            System.out.println("uploadDir = " + uploadDir);
            String pname=photo.getName();

            photoName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+id+pname.substring(pname.lastIndexOf("."));


            photo.write(new File(uploadDir,photoName));


        }catch (Exception e){
            e.printStackTrace();
        }


        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            con=JdbcUtil.getConnection();

            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("update t_emp ")
                    .append("set photo=? ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,photoName);
            ps.setInt(2,id);

            ps.executeUpdate();


            con.commit();

        } catch (Exception e){
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        } finally {
            JdbcUtil.close(con,ps,rs);
        }


        response.sendRedirect(request.getContextPath()+"/list.emp");
    }

    protected void showUploadphoto(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {
        System.out.println("EmpServlet.showUploadphoto()");
        Emp emp=new Emp();
        emp.setId(Integer.parseInt(request.getParameter("id")));
        emp.setName(new String(request.getParameter("name").getBytes("ISO8859-1"), StandardCharsets.UTF_8));
        request.setAttribute("emp",emp);
        request.getRequestDispatcher("/emp/uploadphoto.jsp").forward(request,response);
    }

    protected void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("EmpServlet.modify()");

        Integer id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String salaryStr = request.getParameter("salary");
        Double salary = "".equals(salaryStr.trim())
                ? null
                : Double.parseDouble(salaryStr);
        String sex = request.getParameter("sex");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        String description = request.getParameter("description");

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);


            String sql = new StringBuffer()
                    .append("update t_emp ")
                    .append("set name=?, ")
                    .append("    salary=?, ")
                    .append("    sex=?, ")
                    .append("    edu=?, ")
                    .append("    hobbies=?, ")
                    .append("    description=? ")
                    .append("where id=?")
                    .toString();

            ps = con.prepareStatement(sql);

            ps.setString(1, name);
            ps.setDouble(2, salary);
            ps.setString(3, sex);
            ps.setString(4, edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6, description);
            ps.setInt(7, id);

            ps.executeUpdate();

            con.commit();

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }

        response.sendRedirect(request.getContextPath() + "/list.emp");
    }

    protected void load(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        System.out.println("EmpServlet.load()");

        Emp emp=null;
        Integer id = Integer.parseInt(request.getParameter("id"));

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            con=JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql = new StringBuffer()
                    .append("select * ")
                    .append("from t_emp ")
                    .append("where id=? ")
                    .toString();


            ps = con.prepareStatement(sql);

            ps.setInt(1, id);

            rs = ps.executeQuery();

            if(rs.next()){
                String name = rs.getString("name");
                Double salary = rs.getDouble("salary");
                String sex = rs.getString("sex");
                String edu = rs.getString("edu");
                String hobbies = rs.getString("hobbies");
                String description = rs.getString("description");

                emp=new Emp();
                emp.setId(id);
                emp.setName(name);
                emp.setSalary(salary);
                emp.setSex(sex);
                emp.setEdu(edu);
                emp.setHob(hobbies);
                emp.setDescription(description);
            }

            con.commit();

        } catch (Exception e){
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con,ps,rs);
        }

        request.setAttribute("emp",emp);

        request.getRequestDispatcher("/emp/modify.jsp").forward(request,response);

    }


    protected void remove(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("EmpServlet.remove()");

        Integer id = Integer.parseInt(request.getParameter("id"));

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql = new StringBuffer()
                    .append("delete from t_emp ")
                    .append("where id=? ")
                    .toString();

            ps = con.prepareStatement(sql);

            ps.setInt(1, id);

            ps.executeUpdate();

            con.commit();

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }

        response.sendRedirect(request.getContextPath() + "/list.emp");

    }


    protected void list(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        System.out.println("EmpServlet.list()");

        List<Emp> emps = new ArrayList<Emp>();

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql = new StringBuffer()
                    .append("select * ")
                    .append("from t_emp ")
                    .toString();

            ps = con.prepareStatement(sql);

            rs = ps.executeQuery();

            while (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setSex(rs.getString("sex"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                emp.setDescription(rs.getString("description"));
                emp.setPhoto(rs.getString("photo"));
                emps.add(emp);
            }

            con.commit();

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }

        request.setAttribute("emps", emps);



        request.getRequestDispatcher("/emp/list.jsp").forward(request, response);
        //错
        // response.sendRedirect(request.getContextPath()+"/emp/list.jsp");
    }


    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("EmpServlet.add()");

        request.setCharacterEncoding("utf-8");


        // response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");


        PrintWriter out = response.getWriter();


        //获得表单提交的数据
        String name = request.getParameter("name");


        // name=new String(name.getBytes("iso8859-1"),"utf-8");

        String salaryStr = request.getParameter("salary");
        Double salary = "".equals(salaryStr.trim())
                ? null
                : Double.parseDouble(salaryStr);
        String sex = request.getParameter("sex");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        String description = request.getParameter("description");


        System.out.println("name = " + name);
        System.out.println("salary = " + salary);
        System.out.println("sex = " + sex);
        System.out.println("edu = " + edu);
        System.out.println("Arrays.toString(hobbies) = " + Arrays.toString(hobbies));
        System.out.println("description = " + description);


        //将数据保存到数据库
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);


            String sql = new StringBuffer()
                    .append("insert into t_emp ")
                    .append("    (name,salary,sex,edu,hobbies,description) ")
                    .append("values ")
                    .append("    (?,?,?,?,?,?) ")
                    .toString();

            ps = con.prepareStatement(sql);

            ps.setString(1, name);
            ps.setDouble(2, salary);
            ps.setString(3, sex);
            ps.setString(4, edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6, description);


            ps.executeUpdate();

            con.commit();

            response.sendRedirect(request.getContextPath() + "/list.emp");
            //错
            // request.getRequestDispatcher("/list.emp").forward(request,response);
        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }


    }
}